package com.xpec.cipher.algorithm;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/**
 * DES加密算法
 * @author shangyong
 *
 */
public class DES {
   
	
	private static Cipher cipher;
	
	private static Key key;
    /**
     * 加密
     * @param key
     * @param data
     * @return
     */
    public static byte[] encrypt(byte[] byteKey, byte[] data)
    {
    	if(data.length == 0)
    	{
    		return data;
    	}
    	key = toKey(byteKey);
    	
    	try
    	{
    		if(cipher == null)
    			cipher = Cipher.getInstance("DES");
        	
        	cipher.init(Cipher.ENCRYPT_MODE, key);
        	
        	byte[] result = cipher.doFinal(data);
        	
        	return result;
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		throw new IllegalStateException("DES encrypt is illegal");
    	}
    	
    }
    
    /**
     * 解密
     * @param key
     * @param data
     * @return
     */
    public static byte[] decrypt(byte[] byteKey, byte[] data)
    {
    	if(data.length == 0)
    	{
    		return data;
    	}
    	try
    	{
    		key = toKey(byteKey);
    		if(cipher == null)
    			cipher = Cipher.getInstance("DES");
    		cipher.init(Cipher.DECRYPT_MODE, key);
    		byte[] result = cipher.doFinal(data);
    		
    		return result;
    		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    		throw new IllegalStateException("DES decrypt is illegal");
    	}
    	
    	
    }
    
    private static Key toKey(byte[] byteKey)
    {
    	try
    	{
    		DESKeySpec keySpec = new DESKeySpec(byteKey);
        	SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        	SecretKey secretKey = factory.generateSecret(keySpec);
        	return secretKey;
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		throw new IllegalStateException("DES Key is illegal !");
    	}
    }

}
